/**
 * 租户管理
 */
define(function (require, exports, module) {
    var angular = require('angular');
    var ui = require('ui');
    var util = require('util');
    var $ = require('jquery');
    require("pagination");
    require("angular-messages");
    require("angularPublicInterceptor");
    require("/static_public/js/lib/highcharts.cmd");

    angular.module('Tenant', ['angularPublicInterceptor', 'ngMessages'])
        .service('orgs', ['$http', '$q', function ($http, $q) {
            /**
             * 租户列表
             */
            return function (params) {
                var deferred = $q.defer();

                $http.get('/api/index.php?r=mtp/myscrm-organization/get-orgs', {params: params})
                    .success(function (res) {
                        if (res.retCode == 0) {
                            deferred.resolve(res.data);
                        } else {
                            deferred.reject(res.retMsg);
                        }
                    })
                    .error(function () {
                        deferred.reject();
                    });

                return deferred.promise;
            };
        }])
        .service('contracts', ['$http', '$q', function ($http, $q) {
            /**
             * 合同列表
             */
            return function (params) {
                var deferred = $q.defer();

                $http.get('/api/index.php?r=mtp/myscrm-organization/get-contracts-list', {params: params})
                    .success(function (res) {
                        if (res.retCode == 0) {
                            deferred.resolve(res.data);
                        } else {
                            deferred.reject(res.retMsg);
                        }
                    })
                    .error(function () {
                        deferred.reject();
                    });

                return deferred.promise;
            };
        }])
        .service('cancelContract', ['$http', '$q', function ($http, $q) {
            /**
             * 作废合同
             */
            return function (params) {
                var deferred = $q.defer();

                $http.post('/api/index.php?r=mtp/myscrm-organization/cancel-contract', params)
                    .success(function (res) {
                        if (res.retCode == 0) {
                            deferred.resolve(res.data);
                        } else {
                            deferred.reject(res.retMsg);
                        }
                    })
                    .error(function () {
                        deferred.reject();
                    });

                return deferred.promise;
            };
        }])
        .service('updateDeliver', ['$http', '$q', function ($http, $q) {
            /**
             * 更新租户交付信息
             */
            return function (params) {
                var deferred = $q.defer();

                $http.post('/api/index.php?r=mtp/myscrm-organization/update-deliver-info', params)
                    .success(function (res) {
                        if (res.retCode == 0) {
                            deferred.resolve(res.data);
                        } else {
                            deferred.reject(res.retMsg);
                        }
                    })
                    .error(function () {
                        deferred.reject();
                    });

                return deferred.promise;
            };
        }])
        .service('editContract', ['$http', '$q', function ($http, $q) {
            /**
             * 新增或更改合同
             */
            return function (params) {
                var deferred = $q.defer();

                $http.post('/api/index.php?r=mtp/myscrm-organization/save-contract', params)
                    .success(function (res) {
                        if (res.retCode == 0) {
                            deferred.resolve(res.data);
                        } else {
                            deferred.reject(res.retMsg);
                        }
                    })
                    .error(function () {
                        deferred.reject();
                    });

                return deferred.promise;
            };
        }])
        .service('allPackages', ['$http', '$q', function ($http, $q) {
            /**
             * 所有的包信息
             */
            return function (params) {
                var deferred = $q.defer();

                $http.post('/api/index.php?r=mtp/myscrm-organization/get-all-packages', params)
                    .success(function (res) {
                        if (res.retCode == 0) {
                            deferred.resolve(res.data);
                        } else {
                            deferred.reject(res.retMsg);
                        }
                    })
                    .error(function () {
                        deferred.reject();
                    });

                return deferred.promise;
            };
        }])
        .service('packagesByOrg', ['$http', '$q', function ($http, $q) {
            /**
             * 所有的包信息
             */
            return function (params) {
                var deferred = $q.defer();

                $http.post('/api/index.php?r=mtp/myscrm-organization/get-packages-by-org', params)
                    .success(function (res) {
                        if (res.retCode == 0) {
                            deferred.resolve(res.data);
                        } else {
                            deferred.reject(res.retMsg);
                        }
                    })
                    .error(function () {
                        deferred.reject();
                    });

                return deferred.promise;
            };
        }])
        .controller('tenantCtl', [
            '$scope',
            'appservice',
            'orgs',
            'contracts',
            'cancelContract',
            'updateDeliver',
            'editContract',
            'allPackages',
            'packagesByOrg',
            function ($scope, appservice, orgs, contracts, cancelContract, updateDeliver, editContract, allPackages, packagesByOrg) {
                appservice.name = '明源云链-租户管理';

                $scope.setAside = function (tenant, contract, sucCallback) {
                    util.confirm('确定作废吗？', {
                        ok: function () {
                            cancelContract({orgname: tenant.UniqueName, contract_id: contract.ContractId})
                                .then(function () {
                                    contract.Status = 2;
                                    ui.showSucTip('作废成功');

                                    sucCallback && sucCallback();
                                });
                        }
                    });
                };

                $scope.editContract = function (contract, dialog, dialogScope, organizationId) {
                    var packages = contract.packages;

                    var pkg;
                    for (var i = 0; pkg = packages[i]; i++) {
                        pkg.package_id = pkg.id;
                    }

                    return editContract({
                        contract_id: contract.ContractId,
                        contract_num: contract.ContractNum,
                        party_a: contract.PartyA,
                        contract_type: contract.ContractType,
                        begin_on: contract.BeginOn,
                        end_on: contract.EndOn,
                        organization_id: organizationId,
                        auth_info: packages
                    })
                        .then(function () {
                            dialog.close();

                            ui.showSucTip();
                        });
                };

                $scope.showEditTenant = function (item, dialog, dialogScope) {
                    $scope.curTenant = item;

                    dialogScope.setAside = function (contract) {
                        $scope.setAside(item, contract, function () {
                            getTenantInfo();
                        });
                    };

                    dialogScope.editContract = function (contract, innerDialog, innerDialogScope) {
                        $scope.editContract(contract, innerDialog, innerDialogScope, item.Id).
                            then(function () {
                                getTenantInfo();
                            });

                        return false;
                    };

                    dialogScope.onShowCreateContract = function (tenantData, dialog, dialogScope) {
                        allPackages().then(function (data) {
                            for (var key in data) {
                                if (data.hasOwnProperty(key)) {
                                    data[key].total_num = 0;
                                }
                            }

                            dialogScope.data.ContractType = tenantData.contracts.length > 0 ? 2 : 1;

                            dialogScope.data.packages = data;

                            setTimeout(function () {
                                dialog.reset();
                            }, 0);
                        });
                    };

                    dialogScope.createContract = function (contract, $dialog, $dialogScope) {
                        $scope.editContract(contract, $dialog, $dialogScope, item.Id).
                            then(function () {
                                getTenantInfo();
                            });

                        return false;
                    };

                    var getTenantInfo = function () {
                        contracts({orgname: item.UniqueName})
                            .then(function (data) {
                                dialogScope.data = data;
                            }
                        );

                        packagesByOrg({orgname: item.UniqueName}).then(function (data) {
                            var clolors = ['#FDCF3A', '#E3645B', '#68B1E6', '#31B610', '#FAA103', '#950FAF', '#023FBB'];//黄，红，天空蓝，深绿，橙色，紫色，藏蓝

                            var seriesTotalData = [], seriesUsedData = [], seriesUnUsedData = [];

                            var authorizeTotal = 0;
                            var authorizeUsed = 0;
                            var authorizeUsable = 0;

                            var i = 0;
                            for (var key in data) {
                                if (data.hasOwnProperty(key)) {
                                    var item = data[key];

                                    var totalNum = item.total_num;
                                    var usedNum = item.used_num;
                                    var unUsedNum = totalNum - usedNum;

                                    authorizeTotal += totalNum;
                                    authorizeUsed += usedNum;
                                    authorizeUsable += unUsedNum;

                                    i++;
                                }
                            }

                            var i = 0;
                            for (var key in data) {
                                if (data.hasOwnProperty(key)) {
                                    var item = data[key];
                                    var totalNum = item.total_num;
                                    var usedNum = item.used_num;
                                    var unUsedNum = totalNum - usedNum;

                                    var name = key;

                                    var colorIndex = i % clolors.length;

                                    // 授权
                                    seriesTotalData.push({
                                        name: name + '　' + totalNum,
                                        color: clolors[colorIndex],
                                        y: getPercent(totalNum, authorizeTotal)
                                    });

                                    // 绑定
                                    seriesUsedData.push({
                                        name: name + '　' + usedNum,
                                        color: clolors[colorIndex],
                                        y: getPercent(usedNum, authorizeUsed)
                                    });

                                    // 可用
                                    seriesUnUsedData.push({
                                        name: name + '　' + unUsedNum,
                                        color: clolors[colorIndex],
                                        y: getPercent(unUsedNum, authorizeUsable)
                                    });

                                    i++;
                                }
                            }

                            $('#js_authorize_total').highcharts(getChartData(seriesTotalData, authorizeTotal));
                            $('#js_authorize_used').highcharts(getChartData(seriesUsedData, authorizeUsed));
                            $('#js_authorize_usable').highcharts(getChartData(seriesUnUsedData, authorizeUsable));
                        });
                    };

                    getTenantInfo();
                };

                // 计算两个整数的百分比值
                function getPercent(num, total) {
                    return total <= 0 ? 0 : (Math.round(num / total * 10000) / 100.00);
                }

                function getChartData(data, title) {
                    return {
                        chart: {
                            plotBackgroundColor: null,
                            plotBorderWidth: null,
                            plotShadow: false,
                            spacing: [0, 0, 0, -100],
                            height: 100,
                            width: 280
                        },
                        title: {
                            text: title,
                            align: 'center',
                            verticalAlign: 'middle',
                            floating: true,
                            style: {"fontSize": "20px", 'font-weight': 'bold'},
                            y: 5
                        },
                        tooltip: {
                            pointFormat: '{series.name}: <b>{point.percentage:.2f}%</b>'
                        },
                        plotOptions: {
                            pie: {
                                allowPointSelect: true,
                                cursor: 'pointer',
                                dataLabels: {
                                    enabled: false
                                },
                                showInLegend: true,
                                point: {
                                    events: {
                                        legendItemClick: function () {
                                            return false;   // 目的是屏蔽点击隐藏 serie 的效果
                                        }
                                    }
                                }
                            }
                        },
                        legend: {
                            align: 'right',
                            verticalAlign: 'middle',
                            borderWidth: 0,
                            layout: 'vertical',
                            floating: true,
                            itemStyle: {color: "#333333", cursor: "", fontSize: "12px", fontWeight: "bold"} // 目的是屏蔽连接鼠标箭头
                        },
                        series: [{
                            name: '占比',
                            type: "pie",
                            innerSize: '80%',
                            data: data,
                            states: {
                                hover: {
                                    enabled: false
                                }
                            }
                        }]
                    };
                }

                $scope.saveDeliver = function (data, dialog, dialogScope) {
                    updateDeliver({
                        orgname: data.UniqueName,
                        deliver: data.Deliver,
                        deliver_phone: data.DeliverPhone,
                        custom_manager: data.CustomManager,
                        custom_manager_phone: data.CustomManagerPhone,
                        area: data.Area
                    }).then(function (res) {
                        var index = util.indexOf(data, $scope.list, function (a, b) {
                            return a.Id === b.Id;
                        });

                        if (index > -1) {
                            $scope.list[index] = data;
                        }

                        dialog.close();
                        ui.showSucTip();
                    });

                    return false;
                };

                $scope.query = {
                    page: 1,
                    pageSize: 10,
                    keyword: '',
                    total: 100,
                    execute: function (page) {
                        var query = $scope.query;

                        query.page = page || query.page;

                        return orgs({page: query.page, pageSize: query.pageSize, keyword: query.keyword})
                            .then(function (data) {
                                data = data || {items:[],total:0};

                                query.total = data.total;
                                $scope.list = data.items;
                            });
                    }
                };

                $scope.query.execute();
            }])
});
